<?php

namespace App\Backend\Service;
use Closure;
use Illuminate\Support\Facades\DB;
use App\Libs\TokenLibrary;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Response;
use App\Models\Auth as  AuthModel;
use Illuminate\Support\Facades\Response as ResponseFacade; // 如果需要使用 Facade 的方式调用 Response 类方法
use App\Utils\RedisUtil;
use Illuminate\Support\Facades\Config;
class BaseService
{
    //不需要教养接口
    private $no_need_permission = [
        'LoginController/login',
        'LoginController/captcha',
        'SmsController/sms',
        'SmsController/captchValidate',
        'FileUploadController/upload',
        'LoginController/forgotPassword',
        'RefreshTokenController/getList',
        'CityController/getList',
    ];
    public  $cpage;
    public  $climit;
    public  $userId=0;
    public  $userData=[];
    public  $admin_user=[];
    public function __construct()
    {
        $this->cpage=config('page.page');
        $this->climit=config('page.limit');

/*        $this->domain_name();
        $controller_method=$this->path();
        $res=$this->getTokenUserinfo();
        if(!in_array($controller_method,$this->no_need_permission)){
            
            if(!$res){
                $msg=[
                    'code'=>201,
                    'message'=>'请登录'
                ];
                $result = [
                    'data'=> $msg
                ];
                echo json_encode ($msg);
                exit;
            }



        }*/
        
    }

    public function domain_name()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*');
        // 允许请求的类型
        header('Access-Control-Allow-Methods:POST,GET,PUT,OPTIONS,DELETE');
        // 设置是否允许发送 cookies
        header('Access-Control-Allow-Credentials: true');
        // 设置允许自定义请求头的字段
        header('Access-Control-Allow-Headers: Content-Type,Access-Control-Allow-Origin,Access-token,Content-Length,Accept-Encoding,X-Requested-with, Origin,Access-Control-Allow-Methods,Authorization,token,Accesstoken,Refreshtoken');
        //允许axios获取响应头中的Authorization
       // header('Access-Control-Expose-Headers', 'Authorization');
        //运行客户端携带证书式访问
        //header('Access-Control-Allow-Credentials', 'true');

    }
    /**
     * 根据token 获取id
     */
    protected function getTokenUserinfo()
    {

        $access_token= isset($_SERVER['HTTP_ACCESSTOKEN'])?$_SERVER['HTTP_ACCESSTOKEN']:'';
        $refresh_token= isset($_SERVER['HTTP_REFRESHTOKEN'])?$_SERVER['HTTP_REFRESHTOKEN']:'';
        if(empty($access_token)){
            return false;
        }else{
            $token=$access_token;
        }
        $authToken = trim(ltrim($token,'bearer'));
        $res = TokenLibrary::validateToken($token);
        if($res==false){
            return false;
        }else{

            $this->userId=$res->data->user_id;
            $userinfo=(array)$this->userData=$res->data;
            $data = (array)$res;
            $token_cache = cache()->get("token_backend_".$userinfo['user_id']);
            // dd($authToken);exit;
            if($token_cache != $authToken){
                $this->userId=0;
                return false;
            }
            $userid=$this->userId;
            //redis 验证
            $key="client_backend:".$userid;
            
            //dd($key);
            $data = RedisUtil::getData($key);
            //dd($data);
            if(empty($data)){
                return false;
            }


            $this->checkRule();

            //获取admin的数据
            $userinfo=DB::connection('mysql')->select("SELECT * FROM `sls_admin` where id='$userid'");
            //dd($userinfo);exit;
            if(empty($userinfo)){
                $msg=[
                    'code'=>'401',
                    'message' =>'请最终登录',
                ];
                echo json_encode($msg);
                exit;
            }
            $userinfo=(array)$userinfo['0'];
            $request=Request();
            $userinfo['iat']=$res->iat;
            $request->user_info=$userinfo;


            //dd($request->user_info);exit;
            return true;
        }

    }
    private function path()
    {
        $route = Route::current();
        $controllerName = class_basename($route->getAction()['controller']);
        list($controller, $method) = explode('@', $controllerName);
        $controller_method=$controller.'/'.$method;
        return $controller_method;
    }
    //检查权限
    private function checkRule()
    {
        $user_id=$this->userData->user_id;
        $admin_user = DB::connection('mysql')->select("SELECT * FROM sls_admin WHERE id='$user_id' limit 1");
        $admin_user=(array)$admin_user['0'];
        $this->admin_user=[
            'id'=>$admin_user['id'],
            'username'=>$admin_user['username'],
            'nickname'=>$admin_user['nickname'],
            'mobile'=>$admin_user['mobile'],
        ];
        $path=$this->path();
        if($admin_user['role_id'] != 1 && !$this->checkRight($admin_user['role_id'], $path)){
            $msg=[
                    'code'=>301,
                    'message'=>'没有权限'
                ];
            echo json_encode($msg);
            exit;
        }  

        

    }


    /**
     * 验证权限
     */
    private function checkRight($role_id, $path)
    {
        if(empty($role_id) || empty($path)){
            return false;
        }
        //超级管理员
        if($role_id == 1 ){
            return true;
        }
        $role =DB::connection('mysql')->select("SELECT * FROM sls_admin_role WHERE id='$role_id' limit 1");
        if(empty($role)){
            return false;
        }
        $role=$role['0'];
        $where = [
            ['status','=','1'],
            [function($query) use ($role){
                $query->whereIn('id', explode(',',$role->auth));
            }]
        ];
        $routes = array_filter(array_column(AuthModel::where($where)->select('route')->get()->toArray(),'route'));
        if(in_array($path,$routes)) {
            return true;
        }else{
            return false;
        }

    }

     /**
     * 操作成功返回
     */
    protected function success($data = [], $msg = '操作成功', $code = 200)
    {
        if(empty($data)){
            $data=[];
        }

        $alert=[
            'code' => $code,
            'message' => $msg,
            'data' => $data
        ];
        echo json_encode($alert);
        exit;
    }

    /**
     * 操作失败返回
     */
    protected function error($msg = '操作失败', $code = 0, $data = [])
    {
        if(empty($data)){
            $data=[];
        }
        $alert=[
            'code' => $code,
            'message' => $msg,
            'data' => $data
        ];
        echo json_encode($alert);
        exit;
        
    }
    
    
    /**
     * 处理空字符串
     */
    protected function dealEmptyData($data)
    {
         if(!empty($data) && is_array($data)){
           foreach($data as $k=>$v){
               if(empty($v) && $v !== 0){
                   $data[$k] = '';
               }
           }
         }
         return $data;
    }

   


  
    
}
